package hn.cch.async.configuration;

import org.springframework.aop.interceptor.AsyncExecutionAspectSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 配置线程池
 */
@EnableAsync
@Configuration
public class AsyncConfiguration {

    /**
     * 默认线程池：名称是taskExecutor的Executor类型bean
     * @return TaskExecutor
     */
    @Bean(value = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("task-executor-");
        // 线程池核心线程数
        threadPoolTaskExecutor.setCorePoolSize(4);
        // 线程池最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(8);
        // 线程存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 队列最大容量
        threadPoolTaskExecutor.setQueueCapacity(100);
        // 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 单独使用要初始化
        // threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    /**
     * 可以通过@Async(value = "threadPool")指定线程池
     * @return TaskExecutor
     */
    @Bean(value = "threadPool")
    public TaskExecutor threadPool() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("thread-pool-");
        // 线程池核心线程数
        threadPoolTaskExecutor.setCorePoolSize(2);
        // 线程池最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(4);
        // 线程存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 队列最大容量
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 单独使用要初始化
        // threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }




}
